package com.jiangroom.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author dengzaiqiang
 * @createTime 2018/4/17
 * @description token过滤器
 */
public class AccessTokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        /**
         * pre 在请求被路由之前执行
         * routing 在路由请求时调用
         * post 在routing和error过滤器之后调用
         * error 在发生错误时
         */
        return "pre";
    }

    @Override
    public int filterOrder() {
        //数值越小优先级越高
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //过滤是否含有access_token参数
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String accessToken = request.getParameter("access_token");
        if (StringUtils.isEmpty(accessToken)) {
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            return null;
        }
        return null;
    }
}
